import ConfigParser
import os
import urllib

CONFIG_FILE = 'config.ini'
EXE_DEFAULT_ADDRESS = 'http://www.sigep.com.br/SBArrecadacao.zip'
DOCUMENTS_DEFAULT_ADDRESS = 'http://www.sigep.com.br/Documentos.zip'
REMOTE_VERSION_FILE_ADDRESS = 'http://www.sigep.com.br/version.conf'
VERSION_FILE = '.version'

class Configuration(object):
	"""Stores and recover settings from local files"""
	def __init__(self):
		self.config = ConfigParser.ConfigParser()
		config_path = os.curdir + '\\' + CONFIG_FILE
		if os.path.exists(config_path):
			self.config.read(config_path)
		else:
			config_file = open('config.ini', 'w')
			
			config_file.write('[exefile]\n')
			config_file.write('address:\n')
			config_file.write('[documents]\n')
			config_file.write('address:\n')
			config_file.write('[remoteversionfile]\n')
			config_file.write('address:\n')			
			config_file.write('[others]\n')
			config_file.write('#path1:\n')
			config_file.write('#path2:\n')
			config_file.write('#...')
			config_file.close()
			
			#adding the sections with the defaults
			self.config.read(config_path)
			
	
	def get_exefile_address(self):
		return self.config.get("exefile", "address")
	
	def get_documents_address(self):
		return self.config.get("documents", "address")
		
	def get_remote_version_file_address(self):
		return self.config.get("remoteversionfile", "address")
		
	def get_program_name(self):
		return self.config.get('program', 'name')
		
	def get_installed_version(self):
		"""Returns the information about the installed version of the files"""
		version_file_path = os.curdir + '\\' + VERSION_FILE
		if os.path.exists(version_file_path):
			version_file = open(VERSION_FILE, 'r')
			version = version_file.readline().strip('\r\n')
			version_file.close()
			return version
		else:
			version_file = open(VERSION_FILE, 'w')
			#the defaul version is 1
			version_file.write('1')
			version_file.close()
			return '1'
			
	def get_server_version(self):
		try:
			server_version = urllib.urlopen(self.get_remote_version_file_address()).read()
		except IOError:
			server_version = '1'
			
		return server_version.strip('\r\n')
		
	def update_installed_version(self):
		"""Updates the installed version in the local file"""
		version_file_path = os.curdir + '\\' + VERSION_FILE
		os.remove(version_file_path)
		version_file = open(VERSION_FILE, 'w')
		version_file.write(self.get_server_version())
		version_file.close()
		
		
		
		